package service

import (
	"fmt"
	"ginstudydemo.com/main/cache"
	"time"
)

type IStoredTokenService interface {
	AddRefreshToken()
	VerifyRefreshToken()
}

type StoredTokenService struct{}

func NewStoredTokenService() *StoredTokenService {
	return &StoredTokenService{}
}

// AddRefreshToken  添加刷新token到Redis
func (a StoredTokenService) AddRefreshToken(key string, token string, expiration time.Duration) error {
	fmt.Printf("AddRefreshToken  - Token: %s\n", token)
	return cache.Rdb.Set(cache.Rctx, key, token, expiration).Err()
}

// VerifyRefreshToken  验证Redis中的token 是否和传入token匹配
func (a StoredTokenService) VerifyRefreshToken(key string, verifyToken string) (bool, error) {
	res, err := cache.Rdb.Get(cache.Rctx, key).Result()
	// token是否正常获取
	if err != nil {
		return false, err
	}
	// 判断token是否匹配
	if res != verifyToken {
		return false, nil
	}
	fmt.Printf("AddRefreshToken  - Token: %s\n", res)

	return true, nil
}

// DelRefreshToken  删除刷新token
func (a StoredTokenService) DelRefreshToken(key string) error {
	err := cache.Rdb.Del(cache.Rctx, key).Err()
	// token是否正常获取
	if err != nil {
		return err
	}
	return nil
}
